package com.sample.gps;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.loyal.gps.LocationConfig;
import com.loyal.gps.LocationEntity;
import com.loyal.gps.LocationHelper;
import com.loyal.gps.LoopType;

import java.util.List;

public class MainActivity extends AppCompatActivity implements LocationHelper.LocationCallback {
    private static final String TAG = "MainActivity";
    private final String[] PERMISSION_LOCATION = new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
            android.Manifest.permission.ACCESS_FINE_LOCATION};
    private ActivityResultLauncher<Intent> permissionSettingLaunch = null;
    private LocationHelper locationHelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityResultLauncher<String[]> requestPermissionLaunch = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(),
                result -> onSinglePermission(!result.containsValue(false)));
        requestPermissionLaunch.launch(PERMISSION_LOCATION);
        permissionSettingLaunch = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            boolean success = false;
            for (String permission : PERMISSION_LOCATION) {
                boolean granted = ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
                success |= granted;
            }
            onSinglePermission(success);
        });
    }

    private void onSinglePermission(boolean successful) {
        Log.e(TAG, "onSinglePermission: " + successful);
        if (successful) {
            LocationConfig config = new LocationConfig();
            initLocationHelper();
            if (null != locationHelper)
                locationHelper.start(config);
        } else {
            Log.e(TAG, "定位权限被拒绝！");
        }
    }

    private void initLocationHelper() {
        if (null == locationHelper) {
            locationHelper = LocationHelper.getInstance(this);
            locationHelper.setLocationCallback(this);
        }
    }

    public void startLocation(View view) {
        initLocationHelper();
        if (null != locationHelper) {
            LocationConfig config = new LocationConfig();
            locationHelper.start(config);
            Log.e(TAG, "开始定位: ");
        }
    }

    public void startLoopLocation(View view) {
        initLocationHelper();
        if (null != locationHelper) {
            LocationConfig config = new LocationConfig();
            config.setLoopType(LoopType.REPEAT);
            locationHelper.start(config);
            Log.e(TAG, "开始定位: ");
        }
    }

    public void stopLocation(View view) {
        initLocationHelper();
        if (null != locationHelper) {
            locationHelper.stop();
            Log.e(TAG, "结束定位: ");
        }
    }

    @Override
    public void onLocationCallback(@NonNull LocationEntity entity) {
        Log.e(TAG, "onLocation: " + entity);
    }

    @Override
    public void onProviderNotEnable(@NonNull List<String> disableList) {
        Log.e(TAG, "onProviderNotEnable: " + disableList);
        if (disableList.contains(LocationManager.GPS_PROVIDER)) {
            showGpsDialog();
        } else if (disableList.contains(LocationManager.NETWORK_PROVIDER)) {
            showNetworkDialog();
        } else if (disableList.contains(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            showPermissionDialog();
        }
    }

    private void showNetworkDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("温馨提示")
                .setMessage("网络不可用，请打开网络！")
                .setCancelable(false)
                .setPositiveButton("确 定", (dialog, which) -> {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                })
                .setNegativeButton("取 消", (dialog, which) -> dialog.dismiss());
        AlertDialog alertDialog = builder.create();
        /*Window window = alertDialog.getWindow();
        if (null != window) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
                window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
            } else {
                window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
        }*/
        alertDialog.show();
    }

    private void showGpsDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("温馨提示")
                .setMessage("无法定位，请打开定位服务")
                .setCancelable(false)
                .setPositiveButton("确 定", (dialog, which) -> {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                })
                .setNegativeButton("取 消", (dialog, which) -> dialog.dismiss());
        AlertDialog alertDialog = builder.create();
        /*Window window = alertDialog.getWindow();
        if (null != window) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
                window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
            } else {
                window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
        }*/
        alertDialog.show();
    }

    private void showPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("温馨提示")
                .setMessage("请授予定位权限")
                .setCancelable(false)
                .setPositiveButton("确 定", (dialog, which) -> {
                    try {
                        Intent intent = new Intent(Settings.ACTION_SETTINGS);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        if (null != permissionSettingLaunch)
                            permissionSettingLaunch.launch(intent);
                    } catch (Exception e) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        if (null != permissionSettingLaunch)
                            permissionSettingLaunch.launch(intent);
                    }
                })
                .setNegativeButton("取 消", (dialog, which) -> dialog.dismiss());
        AlertDialog alertDialog = builder.create();
        /*Window window = alertDialog.getWindow();
        if (null != window) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0新特性
                window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
            } else {
                window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            }
        }*/
        alertDialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locationHelper)
            locationHelper.release();
    }
}
